<template>
  <div>
    <el-dialog
      v-model="isShow"
      :title="$demoi18n('panel.sankeyNodeOrderSetting.dialogTitle')"
      width="400px"
      top="8.4vh"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :class="`${customClass} ${visualThemeClassName} ${xvueNameSpace}`"
    >
      <div class="sankey-node-order-setting-main">
        <el-form
          ref="nodeOrderForm"
          class="form"
          label-position="right"
          :model="nodeOrderForm"
          :rules="rules"
          label-width="85px"
        >
          <VsFormItem label-width="60px">
            <el-radio-group v-model="nodeOrderForm.nodeOptimizationMethod" @change="nodeOptimizationMethodChanged">
              <el-radio label="auto">{{ $demoi18n('panel.label.auto') }}</el-radio>
              <el-radio label="custom">{{ $demoi18n('panel.label.custom') }}</el-radio>
            </el-radio-group>
          </VsFormItem>

          <div v-if="nodeOrderForm.nodeOptimizationMethod === 'custom'" class="config-table">
            <div class="top-btns">
              <el-button
                class="btn-sure"
                size="default"
                type="primary"
                icon="CirclePlus"
                @click="addItem"
              >{{
                $demoi18n('btn.add')
              }}</el-button>
            </div>
            <el-table
              height="480px"
              class="config-panel-table mapping-table"
              :data="nodeOrderForm.orderData"
              :row-style="{ height: '22px' }"
              :header-row-style="{ height: '22px' }"
              :header-cell-style="{ lineHeight: '15px' }"
            >
              <el-table-column type="index" :label="$demoi18n('panel.th.number')" width="45"></el-table-column>
              <el-table-column
                prop="label"
                label="name = (source + target)"
                min-width="110"
                :render-header="renderTableHeader"
              >
                <template #default="scope">
                  <VsFormItem
                    :prop="`orderData[${scope.$index}].value`"
                    :rules="
                      generateRules({
                        required: false,
                      })
                    "
                  >
                    <ValueInputer v-model:value="scope.row.value" :enum-values="valueList" />
                  </VsFormItem>
                </template>
              </el-table-column>

              <el-table-column
                prop="isActived"
                :label="$demoi18n('word.operation')"
                width="70"
                align="center"
                :render-header="renderTableHeader"
              >
                <template #default="scope">
                  <el-button
                    icon="SortUp"
                    :link="true"
                    type="primary"
                    :disabled="scope.$index === 0"
                    @click.stop="moveUp(scope.$index, scope.row)"
                  ></el-button>
                  <el-button
                    icon="SortDown"
                    :link="true"
                    type="primary"
                    style="margin-left: 1px;"
                    :disabled="scope.$index === nodeOrderForm.orderData.length - 1"
                    @click.stop="moveDown(scope.$index, scope.row)"
                  ></el-button>
                  <el-button
                    icon="Delete"
                    :link="true"
                    type="primary"
                    style="margin-left: 1px;"
                    @click.stop="delItem(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <div class="action-button-group">
          <el-button class="button-sure" size="small" type="primary" @click="handleSave()">{{
            $demoi18n('btn.confirm')
          }}</el-button>
          <el-button class="button-cancel" size="small" @click="cancel()">{{ $demoi18n('btn.close') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="jsx">
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import { generateRules, genRequireRule } from '@/utils/rules';
import { convertFormData } from '@/utils/util';
import dataModel from '@/models/panel-config-data.js';
import { merge } from 'lodash';

export default {
  name: 'ThresholdSetting',
  components: { ValueInputer },
  props: ['form', 'config'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      xvueTheme: window._adoPremise.uc.theme,
      customClass: `sankey-node-order-setting sankey-node-order-setting-${window._adoPremise.uc.theme || 'light'}`,
      isShow: false,
      nodeOrderForm: {},
      valueList: [],
      rules: {
        thresholdDataType: genRequireRule({
          label: this.$demoi18n('word.valueType'),
        }),
      },
    };
  },
  computed: {},
  watch: {},
  methods: {
    genRequireRule,
    generateRules,
    addItem() {
      this.nodeOrderForm.orderData.push({ value: '', byUser: true });
    },
    moveUp(index) {
      if (index > 0) {
        const temp = this.nodeOrderForm.orderData[index - 1];
        this.nodeOrderForm.orderData.splice(index - 1, 1);
        this.nodeOrderForm.orderData.splice(index, 0, temp);
      }
    },
    moveDown(index) {
      const temp = this.nodeOrderForm.orderData[index + 1];
      this.nodeOrderForm.orderData.splice(index + 1, 1);
      this.nodeOrderForm.orderData.splice(index, 0, temp);
    },
    delItem(scope) {
      let { orderData } = this.nodeOrderForm;
      for (let i = 0; i < orderData.length; i++) {
        if (scope === orderData[i]) {
          orderData = orderData.splice(i, 1);
        }
      }
    },

    // 对orderData 进行重复值校验
    checkLimit() {
      const data = this.nodeOrderForm.orderData;
      const list = data.map(n => n.value).filter(n => n);
      const listU = Array.from(new Set(list));
      if (list.length !== listU.length) {
        this.$message.error(this.$demoi18n('message.noDuplicatedData'));
        return false;
      }
      return true;
    },
    openDialog() {
      // 初始化深拷贝
      const { nodeOptimizationMethod, orderData, nodeOrderObj } = JSON.parse(JSON.stringify(this.form));
      this.nodeOrderForm = {
        nodeOptimizationMethod,
        orderData,
        nodeOrderObj,
      };
      this.initNodeData();
      this.isShow = true;
    },
    nodeOptimizationMethodChanged(value) {
      if (value === 'custom') {
        this.getApiData();
      }
    },
    initNodeData() {
      const { nodeOptimizationMethod } = this.nodeOrderForm;
      if (nodeOptimizationMethod === 'auto') {
        return;
      }
      this.checkSameConfig();

      this.getApiData();
    },

    // apiCode,tableData等相关数据是否相同，不同则清空orderData
    checkSameConfig() {
      const { nodeOrderObj } = this.nodeOrderForm;
      let isSame = false;
      const { apiCode, tableData, dataSourceType, dataPackage } = this.config.config.data;
      const flag = (nodeOrderObj && nodeOrderObj.dataSourceType === dataSourceType) &&
                    (nodeOrderObj.apiCode === apiCode || nodeOrderObj.dataPackage === dataPackage) &&
                    (nodeOrderObj.tableData && nodeOrderObj.tableData.length);

      if (flag) {
        let isSameTableData = true;
        for (let index = 0; index < nodeOrderObj.tableData.length; index++) {
          const item = nodeOrderObj.tableData[index];
          const findSameOne = tableData.find(t => item.field === t.field && item.mapping === t.mapping);
          if (!findSameOne) {
            isSameTableData = false;
            break;
          }
        }
        if (isSameTableData) {
          isSame = true;
        }
      }

      // 不同则清空数据
      if (!isSame) {
        this.nodeOrderForm.orderData = [];
      }
    },

    // xMiner公共数据库需要加上datasourceCode和isCommonDatasource参数
    addCommonSourceParamsxMinerPublicDatabase(params) {
      const { dataSource } = this.config.config.data;
      params.isCommonDatasource = true;
      params.datasourceCode = dataSource;
      return params;
    },
    getApiData() {
      const { orderData } = this.nodeOrderForm;
      const { apiCode, tableData, dataSourceType, dataPackage } = this.config.config.data;

      // 记录本次的dataSourceType等信息到nodeOrderObj
      this.nodeOrderForm.nodeOrderObj = {
        apiCode,
        tableData,
        dataSourceType,
        dataPackage,
      };
      if (['xMiner', 'xMinerPublicDatabase', 'fabric', 'Dac'].includes(dataSourceType)) {
        if (!apiCode) {
          return;
        }
        const method = `getChartData${dataSourceType}`;
        let params = {
          apiCode,
          propertyMapping: convertFormData(tableData),
        };

        // 公用数据库增加传参
        if (this[`addCommonSourceParams${dataSourceType}`]) {
          params = this[`addCommonSourceParams${dataSourceType}`](params);
        }
        dataModel[method](params)
          .then(result => {
            this.setValueList(result);
            const arr = this.mergeData(orderData, this.valueList);
            this.nodeOrderForm.orderData = arr;
          });
      }
      if (dataSourceType === 'xTag') {
        if (!dataPackage) {
          return;
        }
        const method = 'getChartDataxTag';
        const params = {
          conditions: [],
          propertyMapping: convertFormData(tableData),
          sqlParams: [],
        };
        dataModel[method](params, this.config.config.data)
          .then(result => {
            this.setValueList(result);
            const arr = this.mergeData(orderData, this.valueList);
            this.nodeOrderForm.orderData = arr;
          });
      }
    },
    mergeData(orderData = [], data = []) {
      // 转化成显示的值
      const list = data.map(item => ({ value: item.value }));

      const arr = this._mergeArr(orderData, list);
      return arr;
    },
    _mergeArr(orderData, list) {
      // 制作拷贝，删除byUser属性，用于与list判断
      const orderDataCopy = JSON.parse(JSON.stringify(orderData));
      orderDataCopy.forEach(item => {
        delete item.byUser;
      });
      list.forEach(item => {
        const findSame = orderDataCopy.find(d => JSON.stringify(d) === JSON.stringify(item));
        if (!findSame) {
          orderData.push(item);
        }
      });
      return orderData;
    },

    // 设置自定义节点排序数据
    setOrderDataByAPI(data) {
      if (data && data.length) {
        if (data.length > 200) {
          data.length = 200;
        }
        const list = data.map(item => ({ value: `${item.source}-${item.target}` }));
        this.nodeOrderForm.orderData = list;
      }
    },

    // 获取下拉列表
    setValueList(result) {
      if (result && result.length) {
        const sources = result.map(n => n.source);
        const targets = result.map(n => n.target);
        const valueListSet = new Set([...sources, ...targets]);

        const valueList = [];
        valueListSet.forEach(value => {
          valueList.push({
            label: value,
            value: value,
          });
        });
        this.valueList = valueList;
      } else {
        this.valueList = [];
      }
    },
    cancel() {
      this.isShow = false;
    },
    handleSave() {
      this.$refs.nodeOrderForm.validate(valid => {
        if (!valid) {
          return;
        }
        merge(this.form, this.nodeOrderForm);
        this.cancel();
      });
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
  },
};
</script>

<style lang="less">
@import '../../../common/color-picker-panel.less';
</style>
<style lang="less">
.sankey-node-order-setting {
  .el-dialog__body {
    padding-top: 16px;
  }
}
</style>
<style lang="less" scoped>
.sankey-node-order-setting {
  .sankey-node-order-setting-main {
    .form {
      width: 100%;
      :deep(.el-form-item) {
        margin-bottom: 0;
      }
      .config-table {
        .top-btns {
          margin-bottom: 10px;
        }
        :deep(.el-table) {
          .el-form-item__error {
            top: 100%;
            padding-top: 0;
          }
          .is-error {
            margin-bottom: 15px;
          }
          .cell {
            padding: 0 3px !important;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            .threshold-column {
              display: flex;
              align-items: center;
            }
            .el-input__inner {
              padding: 0 5px !important;
            }
          }
          td,
          th {
            padding: 5px 0 !important;
          }
          th div {
            display: inline;
            line-height: 15px;
          }
          .el-table__row > td {
            border: none;
          }
        }
        :deep(.el-form-item__content) {
          margin-left: 0 !important;
        }
      }
    }
  }

  .action-button-group {
    text-align: right;
    padding-top: 20px;
    .button-sure {
      padding: 9px 35px;
      border-radius: 0;
    }
    .button-cancel {
      padding: 9px 35px;
      border-radius: 0;
    }
  }
}
.icon-library-dialog-dark {
  .icon-library-main {
    background-color: #071f30;
  }
  .action-button-group {
    .button-sure {
      background-color: #0eb4c2;
      color: #fff;
    }
    .button-cancel {
      background-color: #064559;
      border-color: #064559;

      color: #fff;
    }
  }
}
</style>

<style lang="less">
@font_color_dark: #98cae6;
@borderColor_dark: #116584;
@textColor_dark: #ffffff;
@bgColor_dark: #000c17;
@font_color_active_dark: #00f0ff;
@background_color_dark: #071f30;
.sankey-node-order-setting-dark {
  .el-dialog__header {
    background: #183c5a;
    .el-dialog__title {
      color: #fff;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #fff;
      }
    }
  }

  .el-dialog__body {
    background: #0e2b40;

    .el-form-item__label {
      color: @font_color_dark;
    }

    .el-input {
      .el-input__inner {
        border-color: @borderColor_dark;
        color: @textColor_dark;
        background-color: @bgColor_dark;
      }

      .el-input__icon {
        color: @borderColor_dark;
      }
    }

    .el-radio-group {
      .el-radio {
        color: @textColor_dark;

        .el-radio__input {
          .el-radio__inner {
            border-color: @font_color_active_dark;
            background-color: unset;
          }
        }

        .is-checked {
          .el-radio__inner {
            &::after {
              background-color: @font_color_active_dark;
            }
          }
        }

        .el-radio__label {
          color: #fff;
        }
      }
      .is-checked {
        .el-radio__label {
          color: #00f0ff;
        }
      }
    }

    .el-switch__core {
      background-color: #064559;
      border-color: #064559;
    }

    .el-switch.is-checked {
      .el-switch__core {
        background-color: #0eb4c2;
        border-color: #0eb4c2;
      }
    }

    .el-color-picker {
      .el-color-picker__trigger {
        border-color: @borderColor_dark;
      }
    }

    // 表格
    .config-panel-table {
      color: @font_color_dark;
      background-color: @background_color_dark;

      &::before {
        background-color: @background_color_dark;
      }

      .cell {
        padding: 0 3px !important;
      }
      td,
      th {
        padding: 5px 0 !important;
      }

      .el-table__header {
        th {
          background-color: #122b40 !important;
          border-color: #122b40;
          color: @font_color_dark;
        }
      }

      .el-table__body {
        tr {
          td {
            background-color: @background_color_dark;
            border-color: @background_color_dark;

            .icon-library-open {
              background-color: unset;
              border-color: #0eb4c2;
            }
          }
        }
      }

      .el-table__empty-block {
        background-color: #093758;

        .el-table__empty-text {
          color: @font_color_active_dark;
        }
      }
    }

    .button-sure {
      background-color: #0eb4c2;
      border-color: #0eb4c2;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }

    .button-cancel {
      background-color: #064559;
      border-color: #064559;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }
  }
}
</style>
